package fan.project3_pksystem.WebSocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import fan.project3_pksystem.Module.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class FindPlayerApi extends TextWebSocketHandler {
    ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private FindPlayerQueue findPlayerQueue;

    @Autowired
    private OnLinePlayers onlinePlayers;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private GameRoomManager gameRoomManager;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            UserInfo userInfo = (UserInfo) session.getAttributes().get("userInfo");
            System.out.println(userInfo.getUserName()+"玩家进入房间页面 ");
//            处理多开问题
            if (onlinePlayers.getHubOl(userInfo.getId()) != null|| onlinePlayers.getGameOl(userInfo.getId()) != null) {
                WSResponse wsResponse = new WSResponse();
                wsResponse.setCode("SUCCESS");
                wsResponse.setMessage("禁止用户多开!!! 严重者将予以封号处理");
                System.out.println("监测到用户在大厅多开");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(wsResponse)));

                return;
            }
//            玩家上线
            onlinePlayers.addHubOl(userInfo.getId(), session);
            System.out.println(userInfo.getUserName() + " 玩家进入大厅");
        } catch (NullPointerException e) {
            System.out.println("用户未登录但试图连接游戏");
            WSResponse wsResponse = new WSResponse();
            wsResponse.setCode("SUCCESS");
            wsResponse.setMessage("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(wsResponse)));
        }
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("玩家匹配接口收到:" + message.getPayload());
//        session.sendMessage(new TextMessage("你好!!!!!!!!!!!!!!!!!!!!!!!!1"));

        UserInfo userInfo = (UserInfo) session.getAttributes().get("userInfo");
        Request request = objectMapper.readValue(message.getPayload(), Request.class);
        WSResponse wsResponse = new WSResponse();
        if(request.getMessage().equals("startFindPlayer")) {
//            玩家开始匹配
            wsResponse.setCode("SUCCESS");
            wsResponse.setMessage("start find");

//            加入匹配队列
            findPlayerQueue.add(userInfo);

        }else if (request.getMessage().equals("stopFindPlayer")) {
            findPlayerQueue.remove(userInfo);
            wsResponse.setCode("SUCCESS");
            wsResponse.setMessage("stop find");


        }
//        发送玩家状态
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(wsResponse)));



    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        try {
            UserInfo userInfo = (UserInfo) session.getAttributes().get("userInfo");
//            检查是否是多开账号
            if(onlinePlayers.getHubOl(userInfo.getId())!=session){
                return;
            }
//            如果在匹配队列就取消掉
            findPlayerQueue.remove(userInfo);

            onlinePlayers.removeHubOl(userInfo.getId());
        } catch (NullPointerException e) {
            System.out.println("用户未登录但试图连接游戏");
            WSResponse wsResponse = new WSResponse();
            wsResponse.setCode("ERROR");
            wsResponse.setMessage("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(wsResponse)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        UserInfo userInfo = (UserInfo) session.getAttributes().get("userInfo");
        try {

//            处理多开
            if(onlinePlayers.getHubOl(userInfo.getId())!=session){
                System.out.println("多开用户已被关闭");
                return;
            }
            //      如果因玩家进入游戏而关闭则不作退出队列操作,防止抛异常
            if(gameRoomManager.getPlayerIsOnGame(userInfo.getId())){
                onlinePlayers.removeHubOl(userInfo.getId());
                return;
            }
            findPlayerQueue.remove(userInfo);
            onlinePlayers.removeHubOl(userInfo.getId());
        } catch (NullPointerException e) {
            System.out.println("用户未登录但试图连接游戏");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(Response.success("用户未登录"))));
        }

        System.out.println(userInfo.getUserName()+"玩家离开大厅");
    }
}
